<template>
  <div>
    <div id="map" style="height: 100vh; width: 100vw;"></div>

    <!-- 当前时间显示 -->
    <div style="position: absolute; top: 10px; left: 50%; transform: translateX(-50%); background: rgba(255, 255, 255, 0.7); padding: 5px 10px; border-radius: 5px; font-weight: bold;">
      当前时间：{{ currentTime }}
    </div>

    <!-- 经纬度显示 -->
    <div v-if="coordinates" style="position: absolute; top: 10px; left: 10px; background: rgba(255, 255, 255, 0.7); padding: 5px; border-radius: 5px;">
      <strong>经度:</strong> {{ coordinates.lng.toFixed(5) }} <strong>纬度:</strong> {{ coordinates.lat.toFixed(5) }}
    </div>

    <!-- 提示信息 -->
    <div v-if="alertMessage" style="position: absolute; top: 60px; left: 10px; background: rgba(255, 255, 255); padding: 10px; border-radius: 5px; font-size: 20px; font-family: 'Microsoft YaHei', sans-serif;">
      <button @click="alertMessage = null" style="position: absolute; top: 5px; right: 5px; background: transparent; border: none; font-size: 25px; cursor: pointer;">×</button>
      <div style="padding-top: 25px;">
        <span v-html="alertMessage"></span>
      </div>
    </div>

    <!-- 船舶搜索 -->
    <div style="position: absolute; top: 10px; right: 10px; background: rgba(255, 255, 255, 0.7); padding: 5px; border-radius: 5px; display: flex; align-items: center;">
      <input type="text" v-model="searchName" placeholder="输入船舶名称" style="margin-right: 5px;" />
      <button @click="locateShip">定位船舶</button>
    </div>

    <!-- 地图类型选择下拉框 -->
    <div style="position: absolute; top: 10px; left: 260px; background: rgba(255, 255, 255, 0.7); padding: 5px 10px; border-radius: 5px;">
      <label for="mapType" style="margin-right: 10px;">选择地图类型:</label>
      <select id="mapType" v-model="selectedMapType" @change="changeMapType">
        <option value="normal">普通图</option>
        <option value="satellite">卫星图</option>
        <option value="hybrid">混合图</option>
      </select>
    </div>

    <!-- 船舶详细信息面板 -->
    <div v-if="shipInfoVisible" class="ship-info-panel" style="position: absolute; top: 60px; right: 10px; background: white; padding: 15px; border-radius: 5px; width: 320px; box-shadow: 0 2px 10px rgba(0,0,0,0.2);">
      <div class="close-button" style="text-align: right; margin-bottom: 10px;">
        <button @click="shipInfoVisible = false" style="background: transparent; border: none; font-size: 18px; cursor: pointer;">×</button>
      </div>
      <div class="ship-info-content">
        <div style="font-weight: bold; margin-bottom: 10px; font-size: 16px;">
          船舶详情:
          <span
            @click="copyShipName"
            @mouseenter="hoveringName = true"
            @mouseleave="hoveringName = false"
            :style="{
              cursor: hoveringName ? 'pointer' : 'default',
              textDecoration: hoveringName ? 'underline' : 'none'
            }"
            class="copyable-text"
          >
            {{ selectedShip.NAME || '未知' }}
          </span>
          <!-- 复制成功提示 -->
          <span
            v-if="copySuccess"
            class="copy-toast"
            :style="{
    opacity: copySuccess ? '1' : '0',
    // color: '#007bff'  /* 添加蓝色文字 */
  }"
          >
            已复制!
          </span>
        </div>
        <div class="info-item" style="margin-bottom: 5px;">
          <span style="color: gray; width: 120px; display: inline-block;">经度:</span> {{ selectedShip.LON }}°
        </div>
        <div class="info-item" style="margin-bottom: 5px;">
          <span style="color: gray; width: 120px; display: inline-block;">纬度:</span> {{ selectedShip.LAT }}°
        </div>
        <div class="info-item" style="margin-bottom: 5px;">
          <span style="color: gray; width: 120px; display: inline-block;">长度:</span> {{ selectedShip.LENGTH }}m
        </div>
        <div class="info-item" style="margin-bottom: 5px;">
          <span style="color: gray; width: 120px; display: inline-block;">宽度:</span> {{ selectedShip.WIDTH }}m
        </div>
        <div class="info-item" style="margin-bottom: 5px;">
          <span style="color: gray; width: 120px; display: inline-block;">吃水:</span> {{ selectedShip.DRAFT }}m
        </div>
        <div class="info-item" style="margin-bottom: 5px;">
          <span style="color: gray; width: 120px; display: inline-block;">目的地:</span> {{ selectedShip.DESTINATION }}
        </div>
        <div class="info-item" style="margin-bottom: 5px;">
          <span style="color: gray; width: 120px; display: inline-block;">航向:</span> {{ selectedShip.HEADING }}°
        </div>
        <div class="info-item" style="margin-bottom: 5px;">
          <span style="color: gray; width: 120px; display: inline-block;">对地航迹角:</span> {{ selectedShip.COASTAL_TRACK_ANGLE }}°
        </div>
        <div class="info-item" style="margin-bottom: 5px;">
          <span style="color: gray; width: 120px; display: inline-block;">对地速度:</span> {{ selectedShip.GROUND_SPEED }} knots
        </div>
        <div class="info-item" style="margin-bottom: 15px;">
          <span style="color: gray; width: 120px; display: inline-block;">最后更新时间:</span> {{ selectedShip.GPS_TIME }}
        </div>
        <div class="ship-actions" style="display: flex; justify-content: space-between;">
          <button @click="locateSelectedShip" style="padding: 6px 12px; color: #00afff; border: 1px solid #00afff; border-radius: 4px; cursor: pointer;">定位</button>
          <button @click="showTrack" style="padding: 6px 12px; color: #00afff; border: 1px solid #00afff; border-radius: 4px; cursor: pointer;">轨迹</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as XLSX from 'xlsx';

export default {
  name: 'MapComponent',
  data() {
    return {
      map: null,
      mapZoom: 11,
      coordinates: null,
      shipMarkers: [],
      highlightedMarker: null,
      shipsData: [],         // 用于显示2024/9/27的船
      allShipsData: [],      // 存储所有船舶数据
      alertMessage: null,
      searchName: '',
      selectedMapType: 'satellite',
      temporaryMarkers: [], // 临时添加的非当天船舶标记
      currentTime: '',      // 当前时间
      selectedDate: '2024-09-27', // 默认时间
      shipInfoVisible: false, // 控制船舶信息面板是否显示
      selectedShip: {}, // 当前选中的船舶信息
      hoveringName: false, // 鼠标是否悬停在船舶名称上
      copySuccess: false,  // 复制操作是否成功
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.initMap();
      this.loadData();
      this.updateTime(); // 初始化一次
      setInterval(this.updateTime, 1000); // 每秒更新一次时间
      window.locateShipByName = (name) => {
        this.locateShip(name);
      };
    });
  },
  methods: {
    //
    copyShipName() {
      const shipName = this.selectedShip.NAME || '未知';

      // 使用现代剪贴板API
      navigator.clipboard.writeText(shipName)
        .then(() => {
          this.showCopySuccess();
        })
        .catch(err => {
          console.error('复制失败，尝试传统方法:', err);
          // 回退到传统复制方法
          this.fallbackCopyTextToClipboard(shipName);
        });
    },

    showCopySuccess() {
      this.copySuccess = true;
      setTimeout(() => {
        this.copySuccess = false;
      }, 2000); // 2秒后隐藏提示
    },

    // 传统复制方法，兼容性更好
    fallbackCopyTextToClipboard(text) {
      const textArea = document.createElement("textarea");
      textArea.value = text;

      // 防止影响视图
      textArea.style.position = "fixed";
      textArea.style.top = "-100px";
      textArea.style.left = "-100px";
      textArea.style.width = "1px";
      textArea.style.height = "1px";

      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();

      try {
        document.execCommand('copy');
        this.showCopySuccess();
      } catch (err) {
        console.error('传统复制方法也失败了', err);
      }

      document.body.removeChild(textArea);
    },
    // 更新时间显示
    updateTime() {
      const now = new Date();
      const y = now.getFullYear();
      const m = String(now.getMonth() + 1).padStart(2, '0');
      const d = String(now.getDate()).padStart(2, '0');
      const h = String(now.getHours()).padStart(2, '0');
      const mi = String(now.getMinutes()).padStart(2, '0');
      const s = String(now.getSeconds()).padStart(2, '0');
      this.currentTime = `${y}-${m}-${d} ${h}:${mi}:${s}`;
    },

    // 初始化地图
    initMap() {
      this.map = new BMap.Map('map');
      this.map.centerAndZoom(new BMap.Point(112.890827, 22.94159), this.mapZoom);
      this.map.setCurrentCity('西江');
      this.map.enableScrollWheelZoom(true);
      this.map.enableContinuousZoom(true);
      this.setMapType(this.selectedMapType);

      this.map.addEventListener("mousemove", (e) => {
        this.coordinates = { lng: e.point.lng, lat: e.point.lat };
      });
    },

    // 设置地图类型
    setMapType(type) {
      const mapTypes = {
        normal: BMAP_NORMAL_MAP,
        satellite: BMAP_SATELLITE_MAP,
        hybrid: BMAP_HYBRID_MAP
      };
      this.map.setMapType(mapTypes[type] || BMAP_NORMAL_MAP);
    },

    // 地图切换事件
    changeMapType() {
      this.setMapType(this.selectedMapType);
    },

    // 加载 Excel 数据并解析
    loadData() {
      const filePath = '/files/查询AIS数据for桂林理工.xlsx';
      fetch(filePath)
        .then(res => {
          if (!res.ok) throw new Error('网络响应失败');
          return res.arrayBuffer();
        })
        .then(data => {
          const workbook = XLSX.read(data, { type: 'array' });
          const sheet = workbook.Sheets[workbook.SheetNames[0]];
          if (!sheet) throw new Error('未找到工作表');

          const jsonData = XLSX.utils.sheet_to_json(sheet);
          const allShips = jsonData.map(item => {
            const time = this.formatExcelDate(item['LASTTIME']);
            return {
              LON: item['LON（经度）'] / 1e6,
              LAT: item['LAT（纬度）'] / 1e6,
              NAME: item['NAME'],
              LENGTH: item['LENGTH（长度）'],
              WIDTH: item['WIDTH（宽度）'],
              DRAFT: item['DRAUGHT'],
              DESTINATION: item['DEST（目的地）'],
              HEADING: item['HDG'],
              COASTAL_TRACK_ANGLE: item['COG'],
              GROUND_SPEED: item['SOG'],
              GPS_TIME: time,
              GPS_DATE: time.split(' ')[0]
            };
          });

          this.allShipsData = allShips;
          this.shipsData = allShips.filter(s => s.GPS_DATE === '2024/9/27');
          this.addShipMarkers();
        })
        .catch(err => console.error('加载数据失败:', err));
    },

    // Excel 日期格式化
    formatExcelDate(excelDate) {
      const date = new Date((excelDate - 25569) * 86400 * 1000);
      return date.toLocaleString();
    },

    // 添加船舶标记
    addShipMarkers() {
      this.shipsData.sort((a, b) => new Date(a.GPS_TIME) - new Date(b.GPS_TIME));
      const defaultIcon = this.getDefaultShipIcon();
      const highlightIcon = this.getHighlightShipIcon();

      // 清除所有旧标记（包括临时标记）
      [...this.shipMarkers, ...this.temporaryMarkers].forEach(marker => {
        this.map.removeOverlay(marker);
      });

      this.shipMarkers = [];
      this.temporaryMarkers = [];
      this.highlightedMarker = null;

      this.shipsData.forEach(ship => {
        const point = new BMap.Point(ship.LON, ship.LAT);
        const marker = new BMap.Marker(point, { icon: defaultIcon });
        marker.NAME = ship.NAME;
        marker.SHIP_DATA = ship; // 存储船舶数据到标记
        this.map.addOverlay(marker);
        this.shipMarkers.push(marker);

        marker.addEventListener('click', () => {
          this.handleMarkerClick(marker, ship);
        });
      });
    },

    // 处理标记点击事件（增加地图定位）
    handleMarkerClick(marker, ship) {
      // 地图移动到该船舶位置
      this.map.panTo(marker.getPosition());

      // 重置所有标记为默认图标
      [...this.shipMarkers, ...this.temporaryMarkers].forEach(m => {
        if (m !== marker) {
          m.setIcon(this.getDefaultShipIcon());
        }
      });

      // 设置当前点击标记高亮
      marker.setIcon(this.getHighlightShipIcon());
      this.highlightedMarker = marker;

      // 显示船舶信息面板
      this.showShipInfo(ship);
    },

    // 默认船图标
    getDefaultShipIcon() {
      return new BMap.Icon("/files/dic1.png", new BMap.Size(32, 32));
    },

    // 高亮船图标
    getHighlightShipIcon() {
      return new BMap.Icon("/files/ship-icon.png", new BMap.Size(40, 40));
    },

    // 显示船舶信息面板
    showShipInfo(ship) {
      this.selectedShip = ship;
      this.shipInfoVisible = true;
    },

    // 弹窗显示
    showAlert(message) {
      this.alertMessage = message;
    },

    // 船舶定位（支持从所有船舶中查找）
    locateShip() {
      // 获取搜索框输入的船舶名称，并去除首尾空格
      const name = this.searchName.trim();

      // 在 shipsData 和 allShipsData 中查找名称匹配的船舶信息
      let ship = this.shipsData.find(s => s.NAME === name) || this.allShipsData.find(s => s.NAME === name);

      // 如果没有找到对应船舶，弹出提示并结束函数
      if (!ship) {
        this.showAlert('未找到该船舶');
        return;
      }

      // 创建对应船舶位置的百度地图坐标点
      const point = new BMap.Point(ship.LON, ship.LAT);

      // 地图平移到该船舶的位置
      this.map.panTo(point);

      // 重置所有标记为默认图标
      [...this.shipMarkers, ...this.temporaryMarkers].forEach(marker => {
        marker.setIcon(this.getDefaultShipIcon());
      });

      // 查找当前船舶是否已经有对应的标记对象
      let marker = this.shipMarkers.find(m => m.NAME === ship.NAME);

      // 如果在当前日期数据中没有找到标记，则创建一个临时标记
      if (!marker) {
        // 清除所有现有临时标记
        this.temporaryMarkers.forEach(m => this.map.removeOverlay(m));
        this.temporaryMarkers = [];

        marker = new BMap.Marker(point, { icon: this.getHighlightShipIcon() });
        marker.NAME = ship.NAME;
        marker.SHIP_DATA = ship; // 存储船舶数据到标记
        this.map.addOverlay(marker);
        this.temporaryMarkers.push(marker);

        // 添加点击事件处理
        marker.addEventListener('click', () => {
          this.handleMarkerClick(marker, ship);
        });
      } else {
        // 如果是现有标记，则高亮显示
        marker.setIcon(this.getHighlightShipIcon());
      }

      this.highlightedMarker = marker;

      // 显示船舶信息面板
      this.showShipInfo(ship);
    },

    // 定位当前选中的船舶（备用方法，确保一致性）
    locateSelectedShip() {
      if (!this.selectedShip.LON || !this.selectedShip.LAT) return;

      const point = new BMap.Point(this.selectedShip.LON, this.selectedShip.LAT);
      this.map.panTo(point);
    },

    // 显示船舶轨迹（占位方法，需要根据实际需求实现）
    showTrack() {
      this.showAlert('轨迹功能正在开发中...');
    }
  }
};
</script>
<style>
.copyable-text {
  color: #000;
  cursor: pointer;
  transition: all 0.2s;
}

.copyable-text {
  cursor: pointer;
  transition: color 0.2s; /* 添加平滑过渡效果 */
}

.copyable-text:hover {
  color: #00afff; /* 鼠标悬浮时变为蓝色 */
}
</style>
